package com.sailfish.springbootdemo.service.db2.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.common.DB2Config;
import com.sailfish.springbootdemo.common.DB2TableName;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db2.*;
import com.sailfish.springbootdemo.dao.db4.UserDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db2.*;
import com.sailfish.springbootdemo.pojo.db4.Operate;
import com.sailfish.springbootdemo.pojo.db4.User;
import com.sailfish.springbootdemo.service.db2.PcbCapacityDataService;
import com.sailfish.springbootdemo.service.db4.OperateService;
import com.sailfish.springbootdemo.service.db2.ThirdApiService;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PcbCapacityDataServiceImpl implements PcbCapacityDataService {

    @Autowired
    PcbCapacityDataDao pcbCapacityDataDao;
    @Autowired
    PcbCapacityParamDao pcbCapacityParamDao;
    @Autowired
    PcbCapacityDataHistoryDao pcbCapacityDataHistoryDao;
    @Autowired
    PcbCapacityDataHistory2Dao pcbCapacityDataHistory2Dao;
    @Autowired
    PcbCapacityDataApproveDao pcbCapacityDataApproveDao;
    @Autowired
    PcbApproveProcessDao pcbApproveProcessDao;
    @Autowired
    PcbSonFactoryInfoDao pcbSonFactoryInfoDao;
    @Autowired
    PcbParentFactoryInfoDao pcbParentFactoryInfoDao;
    @Autowired
    PcbCapacityApproveDetailDao pcbCapacityApproveDetailDao;
    @Autowired
    PcbApproveConfigDao pcbApproveConfigDao;
    @Autowired
    UserDao userDao;
    @Autowired
    OperateService operateService;
    @Autowired
    ThirdApiService thirdApiService;

    @Value("${personal.config.env}")
    String env;

    @Override
    public List<PcbCapacityParam> getAll(Long id, Integer pcbCapacityHistoryId, Integer pcbFactoryId, Integer pcbCapacityParamId, Integer pcbParamValueType,
                                         String pcbParamKey, String pcbParamValue, Date createTime, String createUser, Date updateTime, String updateUser,
                                         Integer status, Integer sort) {
        List<PcbCapacityParam> leafs = pcbCapacityParamDao.getParamList(null, DB2TableName.level_sub_type, null, null, null);
        for (PcbCapacityParam param : leafs) {

            List<PcbCapacityData> datas = pcbCapacityDataDao.getAllByLimit(null, pcbCapacityHistoryId, pcbFactoryId, param.getPcbCapacityParamId(), null,
                    null, null, null, null, null, null, null, null);
            for (int i = 0; i < datas.size(); i++) {
                if (datas.get(i).getPcbParamKey().equals(param.getPcbCapacityParamKey())) {
                    param.setPcbCapacityParamValue(datas.get(i).getPcbParamValue());
                }
                if (datas.get(i).getPcbParamKey().equals(param.getPcbCapacityParamKey2())) {
                    param.setPcbCapacityParamValue2(datas.get(i).getPcbParamValue());
                }
                if (datas.get(i).getPcbParamKey().equals(param.getPcbCapacityParamKey3())) {
                    param.setPcbCapacityParamValue3(datas.get(i).getPcbParamValue());
                }
            }
        }
        return leafs;
    }

    @Override
    public List<PcbCapacityDataApprove> getPcbCapacityDataApproveByLimit(PcbCapacityDataApprove search) {
        List<PcbCapacityDataApprove> byLimit = pcbCapacityDataApproveDao.getByLimit(search);
        return byLimit;
    }

    @Override
    public PcbCapacityDataApprove getTemplateStatus() {
        return pcbCapacityDataApproveDao.getSystemStatus();
    }

    @Override
    public List<PcbCapacityData> getAllData(Integer pcbCapacityHistoryId, Integer pcbFactoryId, Integer paramValueType) {
        List<PcbCapacityData> data = new ArrayList<>();
        if (paramValueType == 1) {
            List<PcbCapacityData> data1 = pcbCapacityDataDao.getAllByLimit(null, pcbCapacityHistoryId, pcbFactoryId, null, 1, null, null, null, null, null, null, null, null);
            List<PcbCapacityData> data2 = pcbCapacityDataDao.getAllByLimit(null, pcbCapacityHistoryId, pcbFactoryId, null, 2, null, null, null, null, null, null, null, null);
            data.addAll(data1);
            data.addAll(data2);
        }
        if (paramValueType == 3) {
            List<PcbCapacityData> data3 = pcbCapacityDataDao.getAllByLimit(null, pcbCapacityHistoryId, pcbFactoryId, null, 3, null, null, null, null, null, null, null, null);
            List<PcbCapacityData> data4 = pcbCapacityDataDao.getAllByLimit(null, pcbCapacityHistoryId, pcbFactoryId, null, 4, null, null, null, null, null, null, null, null);
            data.addAll(data3);
            data.addAll(data4);
        }
        for (int i = 0; i < data.size(); i++) {
            Integer paramId = data.get(i).getPcbCapacityParamId();
            PcbCapacityParam byId = pcbCapacityParamDao.getById(paramId);
            data.get(i).setPcbCapacityParam(byId);
        }
        return data;
    }

    @Override
    public List<PcbCapacityDataHistory2> getAllDataHistory(Integer pcbFactoryId, Integer paramValueType, String version) {
        List<PcbCapacityDataHistory2> data = new ArrayList<>();
        if (paramValueType == 1) {
            PcbCapacityDataHistory2 search1 = new PcbCapacityDataHistory2();
            search1.setPcbFactoryId(pcbFactoryId);
            search1.setPcbParamValueType(1);
            search1.setVersion(version);
            List<PcbCapacityDataHistory2> data1 = pcbCapacityDataHistory2Dao.getAllByLimit(search1);
            PcbCapacityDataHistory2 search2 = new PcbCapacityDataHistory2();
            search2.setPcbFactoryId(pcbFactoryId);
            search2.setPcbParamValueType(2);
            search2.setVersion(version);

            List<PcbCapacityDataHistory2> data2 = pcbCapacityDataHistory2Dao.getAllByLimit(search2);
            data.addAll(data1);
            data.addAll(data2);
        }
        if (paramValueType == 3) {
            PcbCapacityDataHistory2 search3 = new PcbCapacityDataHistory2();
            search3.setPcbFactoryId(pcbFactoryId);
            search3.setPcbParamValueType(3);
            search3.setVersion(version);
            List<PcbCapacityDataHistory2> data3 = pcbCapacityDataHistory2Dao.getAllByLimit(search3);
            data.addAll(data3);
            PcbCapacityDataHistory2 search4 = new PcbCapacityDataHistory2();
            search4.setPcbFactoryId(pcbFactoryId);
            search4.setPcbParamValueType(4);
            search4.setVersion(version);
            List<PcbCapacityDataHistory2> data4 = pcbCapacityDataHistory2Dao.getAllByLimit(search4);
            data.addAll(data4);
        }
        for (int i = 0; i < data.size(); i++) {
            Integer paramId = data.get(i).getPcbCapacityParamId();
            PcbCapacityDataHistory2 byId = pcbCapacityDataHistory2Dao.getById(paramId);
            data.get(i).setPcbCapacityDataHistory2(byId);

        }
        return data;
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result delete(Integer id) {
        return null;
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result delete(Integer pcbCapacityHistoryId, Integer pcbFactoryId) {
        try {
            int count = pcbCapacityDataDao.deleteByFactoryId(pcbFactoryId, pcbCapacityHistoryId);
            return ResultUtil.success(null);
        } catch (Exception e) {

            e.printStackTrace();
            ;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result insertOrUpdate(String data) {
        try {
//            PcbCapacityDataApprove systemStatus = pcbCapacityDataApproveDao.getSystemStatus();
//            if(systemStatus == null || !systemStatus.getApproveStatus().equals("已分发")){
//                return ResultUtil.error(500,"模板未分发，不允许修改数据","operate error",null);
//            }
            JSONObject jsonObject = JSONObject.parseObject(data);
            String mode = jsonObject.getString("mode");
            String userId = UserHeaderHolder.getUserId();
            JSONArray jsonArray = jsonObject.getJSONArray("pcbFactoryTemplateList");
            if (jsonArray == null) {
                return ResultUtil.error(500, "pcbFactoryTemplateList 为空", "pcbFactoryTemplateList is null", null);
            }
            DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
            String versionName = dateFormat.format(new Date());
            List<PcbCapacityDataHistory> histories = new ArrayList<>();
            List<PcbCapacityData> entities = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                PcbCapacityData pcbCapacityData = new PcbCapacityData();
                JSONObject jo = (JSONObject) jsonArray.get(i);

                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                pcbCapacityData.setPcbCapacityParamId(jo.get("pcbCapacityParamId") == null ? null : Integer.parseInt(jo.get("pcbCapacityParamId").toString()));
                pcbCapacityData.setPcbCapacityHistoryId(jo.get("pcbCapacityHistoryId") == null ? null : Integer.parseInt(jo.get("pcbCapacityHistoryId").toString()));
                pcbCapacityData.setPcbFactoryId(jo.get("pcbFactoryId") == null ? null : Integer.parseInt(jo.get("pcbFactoryId").toString()));
                pcbCapacityData.setPcbParamValueType(jo.get("pcbParamValueType") == null ? null : Integer.parseInt(jo.get("pcbParamValueType").toString()));
                pcbCapacityData.setPcbParamKey(jo.get("pcbParamKey") == null ? null : jo.get("pcbParamKey").toString());
                pcbCapacityData.setPcbParamValue(jo.get("pcbParamValue") == null ? null : jo.get("pcbParamValue").toString());
                pcbCapacityData.setSort(jo.get("sort") == null ? null : Integer.parseInt(jo.get("sort").toString()));
                pcbCapacityData.setStatus(jo.get("status") == null ? null : Integer.parseInt(jo.get("status").toString()));
                String pcbParamValue = pcbCapacityData.getPcbParamValue();
                if (StringUtils.isBlank(pcbParamValue)) {
                    continue;
                }
                if (jo.get("pcbCapacityDataId") == null) {
                    pcbCapacityData.setCreateTime(new Date());
                    pcbCapacityData.setCreateUser(userId);
                    int count = pcbCapacityDataDao.insert(pcbCapacityData);
                    if (count > 0) {
                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据", 1, 1, new Date(), null, JSONObject.toJSONString(pcbCapacityData)));
                    }
                } else {
                    pcbCapacityData.setPcbCapacityDataId(Integer.parseInt(jo.get("pcbCapacityDataId").toString()));
                    pcbCapacityData.setCreateTime(jo.get("createTime") == null ? null : format.parse(jo.get("createTime").toString()));
                    pcbCapacityData.setUpdateTime(new Date());
                    pcbCapacityData.setUpdateUser(userId);
                    List<PcbCapacityData> oldData = pcbCapacityDataDao.getById(pcbCapacityData.getPcbCapacityDataId());

                    int count = pcbCapacityDataDao.update(pcbCapacityData);
                    if (count > 0) {
                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据", 3, 1, new Date(), JSONObject.toJSONString(oldData), JSONObject.toJSONString(pcbCapacityData)));
                    }
                }
                entities.add(pcbCapacityData);

                PcbCapacityDataHistory pcbCapacityDataHistory = new PcbCapacityDataHistory();
                pcbCapacityDataHistory.setPcbDataVersionName(versionName);
                pcbCapacityDataHistory.setPcbCapacityParamId(jo.get("pcbCapacityParamId") == null ? null : Long.parseLong(jo.get("pcbCapacityParamId").toString()));
                pcbCapacityDataHistory.setPcbFactoryId(jo.get("pcbFactoryId") == null ? null : Integer.parseInt(jo.get("pcbFactoryId").toString()));
                pcbCapacityDataHistory.setPcbParamValueType(jo.get("pcbParamValueType") == null ? null : Integer.parseInt(jo.get("pcbParamValueType").toString()));
                pcbCapacityDataHistory.setPcbParamKey(jo.get("pcbParamKey") == null ? null : jo.get("pcbParamKey").toString());
                pcbCapacityDataHistory.setPcbParamValue(jo.get("pcbParamValue") == null ? null : jo.get("pcbParamValue").toString());
                pcbCapacityDataHistory.setSort(jo.get("sort") == null ? null : Integer.parseInt(jo.get("sort").toString()));
                pcbCapacityDataHistory.setStatus(jo.get("status") == null ? null : Integer.parseInt(jo.get("status").toString()));
                pcbCapacityDataHistory.setCreateTime(new Date());
                histories.add(pcbCapacityDataHistory);
            }

            if (histories.size() > 0) {
                Integer integer = pcbCapacityDataHistoryDao.insertBatch(histories);
            }

            return ResultUtil.success(entities);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    //提交流程
    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result submitApprove(String data) {

        JSONObject jsonObject = JSONObject.parseObject(data);
        String status = jsonObject.getString("status");
        String userId = UserHeaderHolder.getUserId();
        Integer factoryId = jsonObject.getInteger("factoryId");
        if (factoryId == null) {
            return ResultUtil.error(500, "factoryId 为空", "factoryId is null", null);
        }
//        if(StringUtils.isBlank(status)){
//            return ResultUtil.error(500,"参数status为空","param status is null",null);
//        }
        int flowtype = 5;
        PcbSonFactoryInfo sonFactoryInfo = pcbSonFactoryInfoDao.getById(factoryId);
        try {
            PcbApproveConfig approveConfig = pcbApproveConfigDao.getOneByLimit(flowtype, null, factoryId);
            if (approveConfig == null) {
                return ResultUtil.error(500, "请先配置" + "相关流程的审核人员", "Fail", null);
            }
            PcbCapacityDataApprove search = new PcbCapacityDataApprove();
            search.setFactoryId(factoryId);
            search.setFlowType(flowtype);
            search.setStatus(1);
            List<PcbCapacityDataApprove> byLimit = pcbCapacityDataApproveDao.getByLimit(search);
            if (byLimit.size() > 0) {
                for (int i = 0; i < byLimit.size(); i++) {
                    if (byLimit.get(i).getApproveStatus().equals(DB2Config.CapacityDataStatus_Wancheng)) {
                        byLimit.get(i).setStatus(2);//将之前的都作废
                        pcbCapacityDataApproveDao.update(byLimit.get(i));
                    } else {
                        return ResultUtil.error(500, "当前厂家有未处理完成的任务", "", null);
                    }
                }
            }

            //自动创建流程
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String currentDate = sdf.format(new Date());
            PcbCapacityDataApprove byFlowNum = pcbCapacityDataApproveDao.getByFlowNum(currentDate);
            int currentSeq = 0;
            String flowNum = "";
            if (byFlowNum != null) {
                currentSeq = byFlowNum.getSeq();
            }
            currentSeq++;
            //添加审批记录
            flowNum = currentDate + String.format("%05d", currentSeq);
            PcbCapacityDataApprove pcbCapacityDataApprove1 = new PcbCapacityDataApprove();
            pcbCapacityDataApprove1.setFlowNum(flowNum);
            pcbCapacityDataApprove1.setSeq(currentSeq);
            pcbCapacityDataApprove1.setFlowType(flowtype);
            pcbCapacityDataApprove1.setFactoryId(sonFactoryInfo.getPcbSonFactoryId());
            pcbCapacityDataApprove1.setApproveStatus(DB2Config.CapacityDataStatus_FactoryHandle);
            pcbCapacityDataApprove1.setCreateTime(new Date());
            pcbCapacityDataApprove1.setCreateUser(userId);
            pcbCapacityDataApprove1.setApproveUserId(approveConfig.getOperator().toString());
            pcbCapacityDataApprove1.setStatus(1);
            pcbCapacityDataApproveDao.insert(pcbCapacityDataApprove1);
            //添加审批详情
            PcbCapacityApproveDetail pcbCapacityApproveDetail = new PcbCapacityApproveDetail();
            pcbCapacityApproveDetail.setFlowType(flowtype);
            pcbCapacityApproveDetail.setDataId(pcbCapacityDataApprove1.getId());
            pcbCapacityApproveDetail.setApproveNode(DB2Config.CapacityDataStatus_CreateFlow);
            pcbCapacityApproveDetail.setApplyUserId(Integer.parseInt(userId));
            pcbCapacityApproveDetail.setDepartmentId(null);
            pcbCapacityApproveDetail.setSonFactoryId(sonFactoryInfo.getPcbSonFactoryId());
            pcbCapacityApproveDetail.setFileIds(null);
            pcbCapacityApproveDetail.setRemark(null);
            pcbCapacityApproveDetail.setCreateTime(new Date());
            pcbCapacityApproveDetail.setCreateUser(userId);
            pcbCapacityApproveDetail.setNextNodeUserId(approveConfig.getOperator());
            pcbCapacityApproveDetail.setStatus(1);
            pcbCapacityApproveDetail.setSort(100);
            pcbCapacityApproveDetailDao.insert(pcbCapacityApproveDetail);
            //添加审批过程记录
            PcbApproveProcess pcbApproveProcess = new PcbApproveProcess();
            pcbApproveProcess.setApproveType(flowtype);
            pcbApproveProcess.setDataId(pcbCapacityDataApprove1.getId());
            pcbApproveProcess.setOldStatus("");
            pcbApproveProcess.setNewStatus(DB2Config.CapacityDataStatus_CreateFlow);
            pcbApproveProcess.setApproveNode(DB2Config.CapacityDataStatus_CreateFlow);
            pcbApproveProcess.setCreateTime(new Date());
            pcbApproveProcess.setApproveUserId(Integer.parseInt(userId));
            pcbApproveProcess.setApplyToId(null);
            pcbApproveProcessDao.insert(pcbApproveProcess);
            //添加审批详情
            PcbCapacityApproveDetail pcbCapacityApproveDetail2 = new PcbCapacityApproveDetail();
            pcbCapacityApproveDetail2.setFlowType(flowtype);
            pcbCapacityApproveDetail2.setDataId(pcbCapacityDataApprove1.getId());
            pcbCapacityApproveDetail2.setApproveNode(DB2Config.CapacityDataStatus_FactoryHandle);
            pcbCapacityApproveDetail2.setApplyUserId(Integer.parseInt(userId));
            pcbCapacityApproveDetail2.setSonFactoryId(sonFactoryInfo.getPcbSonFactoryId());
            pcbCapacityApproveDetail2.setCreateTime(new Date());
            pcbCapacityApproveDetail2.setCreateUser(userId);
            pcbCapacityApproveDetail2.setStatus(1);
            pcbCapacityApproveDetail2.setSort(100);
            pcbCapacityApproveDetail2.setNextNodeUserId(approveConfig.getOperator2());
            pcbCapacityApproveDetailDao.insert(pcbCapacityApproveDetail2);
            //添加审批过程记录
            PcbApproveProcess pcbApproveProcess2 = new PcbApproveProcess();
            pcbApproveProcess2.setApproveType(flowtype);
            pcbApproveProcess2.setDataId(pcbCapacityDataApprove1.getId());
            pcbApproveProcess2.setOldStatus(DB2Config.CapacityDataStatus_CreateFlow);
            pcbApproveProcess2.setNewStatus(DB2Config.CapacityDataStatus_FactoryHandle);
            pcbApproveProcess2.setApproveNode(DB2Config.CapacityDataStatus_FactoryHandle);
            pcbApproveProcess2.setCreateTime(new Date());
            pcbApproveProcess2.setApplyToId(approveConfig.getOperator());
            pcbApproveProcessDao.insert(pcbApproveProcess2);

//                PcbCapacityDataApprove search= new PcbCapacityDataApprove();
//                search.setFactoryId(factoryId);
//                List<PcbCapacityDataApprove> byLimit = pcbCapacityDataApproveDao.getByLimit(search);
//
//                PcbCapacityDataApprove pcbCapacityDataApprove = new PcbCapacityDataApprove();
//                pcbCapacityDataApprove.setFactoryId(factoryId);
//                pcbCapacityDataApprove.setApproveStatus(status);

//                PcbApproveProcess pcbApproveProcess = new PcbApproveProcess();
//                pcbApproveProcess.setApproveType(3);
//                if(byLimit == null || byLimit.size() == 0){
//                    pcbCapacityDataApprove.setCreateTime(new Date());
//                    pcbCapacityDataApprove.setCreateUser(userId);
//                    int count = pcbCapacityDataApproveDao.insert(pcbCapacityDataApprove);
//                    if(count > 0){
//                        operateService.addOperate(new Operate(2,Integer.parseInt(userId),"PCB工艺能力数据审批",1,1,new Date(),null,JSONObject.toJSONString(pcbCapacityDataApprove)));
//                    }
//
//                    pcbApproveProcess.setOldStatus(null);
//                }
//                else{
//                    PcbCapacityDataApprove old = byLimit.get(0);
//                    String oldData = JSONObject.toJSONString(old);
//                    pcbCapacityDataApprove.setUpdateTime(new Date());
//                    pcbCapacityDataApprove.setCreateTime(old.getCreateTime());
//                    pcbCapacityDataApprove.setCreateUser(old.getCreateUser());
//                    pcbCapacityDataApprove.setUpdateUser(userId);
//                    pcbCapacityDataApprove.setId(old.getId());
//                    int count = pcbCapacityDataApproveDao.update(pcbCapacityDataApprove);
//                    if(count > 0){
//                        operateService.addOperate(new Operate(2,Integer.parseInt(userId),"PCB工艺能力数据审批",3,1,new Date(),oldData,JSONObject.toJSONString(pcbCapacityDataApprove)));
//                    }
//
//                    pcbApproveProcess.setOldStatus(old.getApproveStatus());
//                }
            User userInfo = userDao.getUserInfoById(Integer.parseInt(userId));
            try {
                if (!StringUtils.isBlank(env) && env.equals("h3c_pro")) {
                    List<MailAddress> mailAddressList = new ArrayList<>();
                    if(userInfo.getEmail().contains(",")){
                        String[] emailsArr = userInfo.getEmail().split(",");
                        for (String email : emailsArr) {
                            MailAddress mailAddress = new MailAddress();
                            mailAddress.setMailAddress(email);
                            mailAddress.setType(0);
                            mailAddressList.add(mailAddress);
                        }
                    }else{
                        MailAddress mailAddress = new MailAddress();
                        mailAddress.setMailAddress(userInfo.getEmail());
                        mailAddress.setType(0);
                        mailAddressList.add(mailAddress);
                    }

                    thirdApiService.sendMail(userInfo.getUserName(), "PCB工艺能力数据审批", "PCB工艺能力数据审批",
                            "您有待处理的任务，请及时处理", "10086", mailAddressList, null, null, null, null, 2, null);

                    System.out.println("send mail success");
                }
            } catch (Exception e) {
                System.out.println("send mail error :" + e.getMessage());
            }
//                pcbApproveProcess.setDataId(pcbCapacityDataApprove.getId());
//
//                pcbApproveProcess.setNewStatus(status);
//                pcbApproveProcess.setRemark(null);
//                pcbApproveProcess.setApproveUserId(Integer.parseInt(userId));
//                pcbApproveProcess.setCreateTime(new Date());
//                pcbApproveProcessDao.insert(pcbApproveProcess);

            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            ;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    //更新审批状态
    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result updateApproveStatus(Integer id, String approveStatus, String remark) {
        try {
            if (id == null) {
                return ResultUtil.error(500, "参数id为空", "param id is null", null);
            }
            String userId = UserHeaderHolder.getUserId();
            PcbCapacityDataApprove pcbCapacityDataApprove = new PcbCapacityDataApprove();
            pcbCapacityDataApprove.setId(id);
            pcbCapacityDataApprove.setApproveStatus(approveStatus);
            pcbCapacityDataApprove.setRemark(remark);
            pcbCapacityDataApprove.setApproveUserId(userId);
            PcbCapacityDataApprove old = pcbCapacityDataApproveDao.getById(id);
            String oldData = JSONObject.toJSONString(old);
            int count = pcbCapacityDataApproveDao.update(pcbCapacityDataApprove);
            if (count > 0) {
                PcbCapacityDataApprove newS = pcbCapacityDataApproveDao.getById(id);
                String newData = JSONObject.toJSONString(newS);
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据审批", 3, 1, new Date(), oldData, newData));

                PcbApproveProcess pcbApproveProcess = new PcbApproveProcess();
                pcbApproveProcess.setApproveType(3);
                pcbApproveProcess.setDataId(id);
                pcbApproveProcess.setOldStatus(old.getApproveStatus());
                pcbApproveProcess.setNewStatus(newS.getApproveStatus());
                pcbApproveProcess.setRemark(remark);
                pcbApproveProcess.setApproveUserId(Integer.parseInt(userId));
                pcbApproveProcess.setCreateTime(new Date());
                pcbApproveProcessDao.insert(pcbApproveProcess);
                //发邮件
                User userInfo = userDao.getUserInfoById(Integer.parseInt(userId));
                try {
                    if (!StringUtils.isBlank(env) && env.equals("h3c_pro")) {
                        List<MailAddress> mailAddressList = new ArrayList<>();
                        if(userInfo.getEmail().contains(",")){
                            String[] emailsArr = userInfo.getEmail().split(",");
                            for (String email : emailsArr) {
                                MailAddress mailAddress = new MailAddress();
                                mailAddress.setMailAddress(email);
                                mailAddress.setType(0);
                                mailAddressList.add(mailAddress);
                            }
                        }else{
                            MailAddress mailAddress = new MailAddress();
                            mailAddress.setMailAddress(userInfo.getEmail());
                            mailAddress.setType(0);
                            mailAddressList.add(mailAddress);
                        }
                        String mailContent = "您的PCB能力数据审批已处理，状态由" + old.getApproveStatus() + "变成" + approveStatus;
                        Result result = thirdApiService.sendMail(userInfo.getUserName(), "PCB工艺能力数据审批", "PCB工艺能力数据审批", mailContent
                                , "10086", mailAddressList, null, null, null, null, 2, null);

                        if (result.getCode() != 200) {
                            return result;
                        }
                    }

                } catch (Exception e) {
                    System.out.println("send mail error :" + e.getMessage());
                }
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            ;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
//        return ResultUtil.success(null);
    }

    @Override
    public List<PcbCapacityDataApprove> getApproveList(Integer parentFactoryId, Integer factoryId, String approveStatus, Integer flowType, boolean isAll) {
        PcbCapacityDataApprove search = new PcbCapacityDataApprove();
        final String userId = UserHeaderHolder.getUserId();
        search.setFactoryId(factoryId);
        search.setApproveStatus(approveStatus);
        search.setFlowType(flowType);

        search.setParentFactoryId(parentFactoryId);
        List<PcbCapacityDataApprove> approveList = null;
        if (!isAll)//我的任务
        {
            search.setStatus(1);
            search.setApproveUserId(userId);
            approveList = pcbCapacityDataApproveDao.getByLimit2(search);
        } else {//所有任务
            approveList = pcbCapacityDataApproveDao.getByLimit(search);
        }

        for (int i = 0; i < approveList.size(); i++) {
            PcbCapacityDataApprove approveData = approveList.get(i);
            Integer facId = approveData.getFactoryId();
            PcbSonFactoryInfo factoryInfo = pcbSonFactoryInfoDao.getById(facId);
            approveData.setFactoryInfo(factoryInfo);
            String approveUserId = approveList.get(i).getApproveUserId();
            String createUserId = approveData.getCreateUser();
            String updateUserId = approveData.getUpdateUser();
            if (!StringUtils.isBlank(approveUserId)) {
                User userInfo = userDao.getUserInfoById(Integer.parseInt(approveUserId));
                approveData.setApproveUserInfo(userInfo);
            }
            if (!StringUtils.isBlank(createUserId)) {
                User userInfo = userDao.getUserInfoById(Integer.parseInt(createUserId));
                approveData.setCreateUserInfo(userInfo);
            }
            if (!StringUtils.isBlank(updateUserId)) {
                User userInfo = userDao.getUserInfoById(Integer.parseInt(updateUserId));
                approveData.setUpdateUserInfo(userInfo);
            }
        }
        return approveList;
    }

    @Override
    public Result deleteApproveData(Integer approveDataId) {
        try {
            if (approveDataId == null) {
                return ResultUtil.error(500, "参数approveDataId为空", "param approveDataId is null", null);
            }
            PcbCapacityDataApprove oldData = pcbCapacityDataApproveDao.getById(approveDataId);
            Integer c1 = pcbCapacityApproveDetailDao.deleteByFlowType(oldData.getFlowType(), oldData.getId());
            Integer c2 = pcbApproveProcessDao.deleteByDataId(oldData.getFlowType(), oldData.getId());
            Integer c3 = pcbCapacityDataApproveDao.deleteById(approveDataId);
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            ;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }

    }

    @Override
    public List<PcbApproveProcess> getApproveProcess(Integer dataId, Integer approveType) {
        PcbApproveProcess param = new PcbApproveProcess();
        param.setApproveType(approveType);
        param.setDataId(dataId);
        List<PcbApproveProcess> byLimit = pcbApproveProcessDao.getByLimit(param);
        return byLimit;
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result importH3C(HttpServletRequest req, Integer factoryId, boolean isH3c) throws IOException {
        String userId = UserHeaderHolder.getUserId();
        String typeT = req.getParameter("type");//type==0给出弹框，type=1直接导入
        if (typeT == null) {
            return ResultUtil.error(500, "参数type为空", "param type is null", null);
        }
        try {
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
            MultipartFile file = mRequest.getFile("file");
            Workbook workbook = new XSSFWorkbook(file.getInputStream());
            String str_warning = "";
            Sheet sheet = workbook.getSheetAt(0);
            String type = "";
            String category = "";
            String bigType = "";
            String smallType = "";
            Integer typeId = null;
            Integer categoryId = null;
            Integer bigTypeId = null;
            Integer smallTypeId = null;
            String[] headers = new String[]{"类型", "类别", "大类", "小类"};
            Row rowH = sheet.getRow(2);
            for (int i = 0; i < 4; i++) {
                Cell cell = rowH.getCell(i);
                if (!cell.getStringCellValue().trim().equals(headers[i])) {
                    return ResultUtil.error(500, "导入文件格式不匹配", "template is error", null);
                }
            }

            for (int i = 4; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                Cell cell0 = row.getCell(0);
                String stringCellValue0 = cell0.getStringCellValue();
                //类型
                if (!StringUtils.isBlank(stringCellValue0)) {
                    type = stringCellValue0;
                    List<PcbCapacityParam> types = pcbCapacityParamDao.getAllByLimit(null, type, null, null, null, null, null, 0, null, null, null, null, null);
                    if (types == null || types.size() == 0) {
                        return ResultUtil.error(500, type + "类型不存在", type + " not exist", null);
                    } else {
                        typeId = types.get(0).getPcbCapacityParamId();
                    }
                }
                //类别
                Cell cell1 = row.getCell(1);
                String stringCellValue1 = cell1.getStringCellValue();
                if (!StringUtils.isBlank(stringCellValue0)) {
                    category = stringCellValue1;
                    List<PcbCapacityParam> categorys = pcbCapacityParamDao.getAllByLimit(null, category, null, null, null, null, null, 1, null, null, null, null, null);
                    if (categorys == null || categorys.size() == 0) {
                        return ResultUtil.error(500, category + "类别不存在", category + " not exist", null);
                    } else {
                        categoryId = categorys.get(0).getPcbCapacityParamId();
                    }
                }
                //大类
                Cell cell2 = row.getCell(2);
                String stringCellValue2 = cell2.getStringCellValue();
                if (!StringUtils.isBlank(stringCellValue2)) {
                    bigType = stringCellValue2;
                    List<PcbCapacityParam> bigTypes = pcbCapacityParamDao.getAllByLimit(null, bigType, null, null, null, null, null, 2, null, null, null, null, null);
                    if (bigTypes == null || bigTypes.size() == 0) {
                        return ResultUtil.error(500, bigType + "大类不存在", bigType + " not exist", null);
                    } else {
                        bigTypeId = bigTypes.get(0).getPcbCapacityParamId();
                    }
                }
                Integer valueType1 = 1;
                Integer valueType2 = 2;
                String paramKey1 = "";
                String paramKey2 = "";

                Cell cell3 = row.getCell(3);
                cell3.setCellType(CellType.STRING);
                String stringCellValue3 = cell3.getStringCellValue();
                //小类
                if (!StringUtils.isBlank(stringCellValue3)) {
                    smallType = stringCellValue3;
                    List<PcbCapacityParam> smallTypes = pcbCapacityParamDao.getAllByLimit(bigTypeId, smallType, null, null, null, null, null, 3, null, null, null, null, null);
                    if (smallTypes.size() == 0) {
                        return ResultUtil.error(500, smallType + "小类不存在", bigType + " not exist", null);
                    } else {
                        smallTypeId = smallTypes.get(0).getPcbCapacityParamId();
                        Integer paramType = smallTypes.get(0).getParamType();
                        Cell cell4 = row.getCell(4);
                        Cell cell5 = row.getCell(5);
                        String stringCellValueValue1 = "";
                        String stringCellValueValue2 = "";
                        if (cell4 != null) {
                            stringCellValueValue1 = getValue(cell4.getCellType(), cell4);
                        }
                        if (cell5 != null) {
                            stringCellValueValue2 = getValue(cell5.getCellType(), cell5);
                        }
                        if (paramType == 5) {
                            stringCellValueValue1 = stringCellValueValue1.replace("+", "").replace("-", "").replace("%", "");
                            stringCellValueValue2 = stringCellValueValue2.replace("+", "").replace("-", "").replace("%", "");
                        }
                        if (paramType == 10 || paramType == 11 || paramType == 4 || paramType == 6) {
                            stringCellValueValue1 = stringCellValueValue1.replace("+", "").replace("-", "").replace("/", "").replace("%", "");
                            stringCellValueValue2 = stringCellValueValue2.replace("+", "").replace("-", "").replace("/", "").replace("%", "");
                        }

                        if (!StringUtils.isBlank(stringCellValueValue1)) {
                            boolean flag0 = true;
                            if (paramType == 2)//2.下拉选择
                            {
                                String paramOption = smallTypes.get(0).getParamOptions();
                                if (!StringUtils.isBlank(paramOption)) {
                                    String[] paramOptionArr = paramOption.split(",");
                                    boolean flag = false;
                                    for (int k = 0; k < paramOptionArr.length; k++) {
                                        if (paramOptionArr[k].equals(stringCellValueValue1)) {
                                            flag = true;
                                        }
                                    }
                                    if (!flag) {
                                        flag0 = false;
                                        str_warning += "第" + (i + 1) + "行5列单元格内容不在下拉选项内;";
                                    }
                                }
                            }
                            if (paramType == 4)//4：浮点型*浮点型
                            {

                                if (!stringCellValueValue1.contains("*")) {
                                    flag0 = false;
                                    str_warning += "第" + (i + 1) + "行5列单元格内容不符合浮点型*浮点型;";
                                } else {
                                    String[] split = stringCellValueValue1.split("\\*");
                                    if (split.length == 0 || split.length == 1) {
                                        flag0 = false;
                                        str_warning += "第" + (i + 1) + "行5列单元格内容不符合浮点型*浮点型;";
                                    } else {
                                        boolean ff1 = CommonUtils.isNumeric(split[0]);
                                        boolean ff2 = CommonUtils.isNumeric(split[1]);
                                        if (!ff1 || !ff2) {
                                            flag0 = false;
                                            str_warning += "第" + (i + 1) + "行5列单元格内容不符合浮点型*浮点型;";
                                        }
                                    }
                                }
                            }
                            if (paramType == 5)//5：浮点型/浮点型
                            {

                                if (!stringCellValueValue1.contains("/")) {
                                    flag0 = false;
                                    str_warning += "第" + (i + 1) + "行5列单元格内容不符合浮点型/浮点型;";
                                } else {
                                    String[] split = stringCellValueValue1.split("/");
                                    if (split.length == 0 || split.length == 1) {
                                        flag0 = false;
                                        str_warning += "第" + (i + 1) + "行5列单元格内容不符合浮点型/浮点型;";
                                    } else {
                                        boolean ff1 = CommonUtils.isNumeric(split[0]);
                                        boolean ff2 = CommonUtils.isNumeric(split[1]);
                                        if (!ff1 || !ff2) {
                                            flag0 = false;
                                            str_warning += "第" + (i + 1) + "行5列单元格内容不符合浮点型/浮点型;";
                                        }
                                    }
                                }
                            }
                            if (paramType == 6)//6：公差
                            {
                                if (!stringCellValueValue1.contains(",")) {
                                    boolean ff1 = CommonUtils.isNumeric(stringCellValueValue1);
                                    if (!ff1) {
                                        flag0 = false;
                                        str_warning += "第" + (i + 1) + "行5列单元格内容不符合公差;";
                                    }
                                } else {
                                    String[] split = stringCellValueValue1.split(",");
                                    if (split.length == 0 || split.length == 1) {
                                        flag0 = false;
                                        str_warning += "第" + (i + 1) + "行5列单元格内容不符合公差;";
                                    } else {
                                        boolean ff1 = CommonUtils.isNumeric(split[0]);
                                        boolean ff2 = CommonUtils.isNumeric(split[1]);
                                        if (!ff1 || !ff2) {
                                            flag0 = false;
                                            str_warning += "第" + (i + 1) + "行5列单元格内容不符合公差;";
                                        }
                                    }
                                }
                            }
                            if (paramType == 8)//8：浮点型~浮点型
                            {
                                if (!stringCellValueValue1.contains("~")) {
                                    flag0 = false;
                                    str_warning += "第" + (i + 1) + "行5列单元格内容不符合浮点型~浮点型;";
                                } else {
                                    String[] split = stringCellValueValue1.split("~");
                                    if (split.length == 0 || split.length == 1) {
                                        flag0 = false;
                                        str_warning += "第" + (i + 1) + "行5列单元格内容不符合浮点型~浮点型;";
                                    } else {
                                        boolean ff1 = CommonUtils.isNumeric(split[0]);
                                        boolean ff2 = CommonUtils.isNumeric(split[1]);
                                        if (!ff1 || !ff2) {
                                            flag0 = false;
                                            str_warning += "第" + (i + 1) + "行5列单元格内容不符合浮点型~浮点型;";
                                        }
                                    }
                                }
                            }
                            if (paramType == 10)//10：数值类型[整数]
                            {
                                boolean ff = stringCellValueValue1.matches("\\d+");
                                if (!ff) {
                                    flag0 = false;
                                    str_warning += "第" + (i + 1) + "行5列单元格内容不符合数值类型[整数];";
                                }
                            }
                            if (paramType == 11)//11：数值类型[小数]
                            {
                                boolean ff = stringCellValueValue1.matches("[-+]?[0-9]*\\.?[0-9]+");
                                if (!ff) {
                                    flag0 = false;
                                    str_warning += "第" + (i + 1) + "行5列单元格内容不符合数值类型[小数];";
                                }
                            }
                            PcbCapacityData pcbCapacityData = new PcbCapacityData();
                            pcbCapacityData.setPcbFactoryId(factoryId);
                            pcbCapacityData.setPcbCapacityParamId(smallTypeId);
                            pcbCapacityData.setPcbParamValue(stringCellValueValue1);
                            if (isH3c) {
                                valueType1 = 3;
                                paramKey1 = smallTypes.get(0).getPcbCapacityParamKey3();
                            } else {
                                valueType1 = 1;
                                paramKey1 = smallTypes.get(0).getPcbCapacityParamKey();
                            }
                            if (flag0) {
                                List<PcbCapacityData> allByLimit = pcbCapacityDataDao.getAllByLimit(null, null, factoryId, smallTypeId, valueType1, paramKey1, null, null, null, null, null, null, null);
                                pcbCapacityData.setPcbParamValueType(valueType1);
                                pcbCapacityData.setPcbParamKey(paramKey1);
                                if (allByLimit.size() > 0) {
                                    pcbCapacityData.setPcbCapacityDataId(allByLimit.get(0).getPcbCapacityDataId());
                                    pcbCapacityData.setUpdateUser(userId);
                                    pcbCapacityData.setUpdateTime(new Date());
                                    int count = pcbCapacityDataDao.update(pcbCapacityData);
                                } else {
                                    pcbCapacityData.setCreateTime(new Date());
                                    pcbCapacityData.setCreateUser(userId);
                                    int count = pcbCapacityDataDao.insert(pcbCapacityData);
                                    if (count > 0) {
                                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据批量导入", 1, 2, new Date(), null, JSONObject.toJSONString(pcbCapacityData)));
                                    }
                                }
                            }

                        }
                        if (!StringUtils.isBlank(stringCellValueValue2)) {
                            boolean flag0 = true;
                            if (paramType == 2)//2.下拉选择
                            {
                                String paramOption = smallTypes.get(0).getParamOptions();
                                if (!StringUtils.isBlank(paramOption)) {
                                    String[] paramOptionArr = paramOption.split(",");
                                    boolean flag = false;
                                    for (int k = 0; k < paramOptionArr.length; k++) {
                                        if (paramOptionArr[k].equals(stringCellValueValue2)) {
                                            flag = true;
                                        }
                                    }
                                    if (!flag) {
                                        flag0 = false;
                                        str_warning += "第" + (i + 1) + "行6列单元格内容不在下拉选项内;";
                                    }
                                }
                            }
                            if (paramType == 4)//4：浮点型*浮点型
                            {

                                if (!stringCellValueValue2.contains("*")) {
                                    flag0 = false;
                                    str_warning += "第" + (i + 1) + "行6列单元格内容不符合浮点型*浮点型;";
                                } else {
                                    String[] split = stringCellValueValue2.split("\\*");
                                    if (split.length == 0 || split.length == 1) {
                                        flag0 = false;
                                        str_warning += "第" + (i + 1) + "行6列单元格内容不符合浮点型*浮点型;";
                                    } else {
                                        boolean ff1 = CommonUtils.isNumeric(split[0]);
                                        boolean ff2 = CommonUtils.isNumeric(split[1]);
                                        if (!ff1 || !ff2) {
                                            flag0 = false;
                                            str_warning += "第" + (i + 1) + "行6列单元格内容不符合浮点型*浮点型;";
                                        }
                                    }
                                }
                            }
                            if (paramType == 5)//5：浮点型/浮点型
                            {

                                if (!stringCellValueValue2.contains("/")) {
                                    flag0 = false;
                                    str_warning += "第" + (i + 1) + "行6列单元格内容不符合浮点型/浮点型;";
                                } else {
                                    String[] split = stringCellValueValue2.split("/");
                                    if (split.length == 0 || split.length == 1) {
                                        flag0 = false;
                                        str_warning += "第" + (i + 1) + "行6列单元格内容不符合浮点型/浮点型;";
                                    } else {
                                        boolean ff1 = CommonUtils.isNumeric(split[0]);
                                        boolean ff2 = CommonUtils.isNumeric(split[1]);
                                        if (!ff1 || !ff2) {
                                            flag0 = false;
                                            str_warning += "第" + (i + 1) + "行6列单元格内容不符合浮点型/浮点型;";
                                        }
                                    }
                                }
                            }
                            if (paramType == 6)//6：公差
                            {
                                if (!stringCellValueValue2.contains(",")) {
                                    boolean ff1 = CommonUtils.isNumeric(stringCellValueValue2);
                                    if (!ff1) {
                                        flag0 = false;
                                        str_warning += "第" + (i + 1) + "行6列单元格内容不符合公差;";
                                    }
                                } else {
                                    String[] split = stringCellValueValue2.split(",");
                                    if (split.length == 0 || split.length == 1) {
                                        flag0 = false;
                                        str_warning += "第" + (i + 1) + "行6列单元格内容不符合公差;";
                                    } else {
                                        boolean ff1 = CommonUtils.isNumeric(split[0]);
                                        boolean ff2 = CommonUtils.isNumeric(split[1]);
                                        if (!ff1 || !ff2) {
                                            flag0 = false;
                                            str_warning += "第" + (i + 1) + "行6列单元格内容不符合公差;";
                                        }
                                    }
                                }
                            }
                            if (paramType == 8)//8：浮点型~浮点型
                            {
                                if (!stringCellValueValue2.contains("~")) {
                                    flag0 = false;
                                    str_warning += "第" + (i + 1) + "行6列单元格内容不符合浮点型~浮点型;";
                                } else {
                                    String[] split = stringCellValueValue2.split("~");
                                    if (split.length == 0 || split.length == 1) {
                                        flag0 = false;
                                        str_warning += "第" + (i + 1) + "行6列单元格内容不符合浮点型~浮点型;";
                                    } else {
                                        boolean ff1 = CommonUtils.isNumeric(split[0]);
                                        boolean ff2 = CommonUtils.isNumeric(split[1]);
                                        if (!ff1 || !ff2) {
                                            flag0 = false;
                                            str_warning += "第" + (i + 1) + "行6列单元格内容不符合浮点型~浮点型;";
                                        }
                                    }
                                }
                            }
                            if (paramType == 10)//10：数值类型[整数]
                            {
                                boolean ff = stringCellValueValue2.matches("\\d+");
                                if (!ff) {
                                    flag0 = false;
                                    str_warning += "第" + (i + 1) + "行6列单元格内容不符合数值类型[整数];";
                                }
                            }
                            if (paramType == 11)//11：数值类型[小数]
                            {
                                boolean ff = stringCellValueValue2.matches("[-+]?[0-9]*\\.?[0-9]+");
                                if (!ff) {
                                    flag0 = false;
                                    str_warning += "第" + (i + 1) + "行6列单元格内容不符合数值类型[小数];";
                                }
                            }
                            PcbCapacityData pcbCapacityData = new PcbCapacityData();
                            pcbCapacityData.setPcbFactoryId(factoryId);
                            pcbCapacityData.setPcbCapacityParamId(smallTypeId);
                            pcbCapacityData.setPcbParamValue(stringCellValueValue2);
                            if (isH3c) {
                                valueType2 = 4;
                                paramKey2 = smallTypes.get(0).getPcbCapacityParamKey4();
                            } else {
                                valueType2 = 2;
                                paramKey2 = smallTypes.get(0).getPcbCapacityParamKey2();
                            }
                            if (flag0) {
                                List<PcbCapacityData> allByLimit = pcbCapacityDataDao.getAllByLimit(null, null, factoryId, smallTypeId, valueType2, paramKey2, null, null, null, null, null, null, null);
                                pcbCapacityData.setPcbParamValueType(valueType2);
                                pcbCapacityData.setPcbParamKey(paramKey2);
                                if (allByLimit.size() > 0) {
                                    pcbCapacityData.setPcbCapacityDataId(allByLimit.get(0).getPcbCapacityDataId());
                                    pcbCapacityData.setUpdateUser(userId);
                                    pcbCapacityData.setUpdateTime(new Date());
                                    int count = pcbCapacityDataDao.update(pcbCapacityData);
                                } else {
                                    pcbCapacityData.setCreateTime(new Date());
                                    pcbCapacityData.setCreateUser(userId);
                                    int count = pcbCapacityDataDao.insert(pcbCapacityData);
                                    if (count > 0) {
                                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据批量导入", 1, 2, new Date(), null, JSONObject.toJSONString(pcbCapacityData)));
                                    }
                                }
                            }

                        }
                    }
                }
            }
            if (!StringUtils.isBlank(str_warning) && typeT.equals("0")) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResultUtil.error(500, str_warning, str_warning, null);
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            ;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, "异常:" + e.getMessage(), "exception:" + e.getMessage(), null);
        }
    }

    private static String getValue(CellType cellType, Cell cell) {
        if (cell == null) {
            return "";
        }
        switch (cellType) {
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case NUMERIC: {
                double cur = cell.getNumericCellValue();
                String value = String.valueOf(cur);
                if (value.contains(".0")) {
                    value = value.replace(".0", "");
                }
                return value;
            }
            case BLANK:
            case ERROR:
                return "";
            case STRING:
                return String.valueOf(cell.getRichStringCellValue()).trim();
            case FORMULA:
                try {
                    CellType resultType = cell.getCachedFormulaResultType();
                    return getValue(resultType, cell);
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                    return String.valueOf(cell.getRichStringCellValue());
                }
        }
        return null;
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result clearData(Integer paramId) {
        try {
            String userId = UserHeaderHolder.getUserId();
            PcbCapacityParam oldPcbCapacityParam = pcbCapacityParamDao.getById(paramId);
            List<PcbCapacityData> oldDataList = pcbCapacityDataDao.getAllByLimit(null, null, null, paramId, null, null, null, null, null, null, null, null, null);
            Integer count = pcbCapacityDataDao.deleteByParamId(paramId);
            if (count > 0) {
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据", 2, 2, new Date(), JSONObject.toJSONString(oldDataList), null));
            }
            count = pcbCapacityParamDao.delete(paramId);
            if (count > 0) {
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力模板", 2, 2, new Date(), JSONObject.toJSONString(oldPcbCapacityParam), null));
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            ;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, "异常:" + e.getMessage(), "exception:" + e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result clearDataByFactoryId(Integer factoryId) {
        try {
            String userId = UserHeaderHolder.getUserId();
            List<PcbCapacityData> oldDataList = pcbCapacityDataDao.getAllByLimit(null, null, factoryId, null, null, null, null, null, null, null, null, null, null);
            Integer count = pcbCapacityDataDao.deleteByFactoryId(factoryId, null);
            if (count > 0) {
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据", 2, 2, new Date(), JSONObject.toJSONString(oldDataList), null));
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            ;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, "异常:" + e.getMessage(), "exception:" + e.getMessage(), null);
        }
    }

    @Override
    public boolean checkHasData(Integer paramId) {
        List<PcbCapacityData> oldDataList = pcbCapacityDataDao.getAllByLimit(null, null, null, paramId, null, null, null, null, null, null, null, null, null);
        if (oldDataList != null && oldDataList.size() > 0) {
            return false;
        }
        return true;
    }

    @Override
    public boolean checkHasDataByFactory(Integer factoryId) {
        List<PcbCapacityData> oldDataList = pcbCapacityDataDao.getAllByLimit(null, null, factoryId, null, null, null, null, null, null, null, null, null, null);
        if (oldDataList != null && oldDataList.size() > 0) {
            return false;
        }
        return true;
    }


}
